package com.jushu.storbox.database;

import android.database.Cursor;

import com.jushu.storbox.entities.PreUploadObject;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public class PreUploadDao extends BaseDao implements IBaseDao, IPreUploadDao {
	
	private static final String TAG = PreUploadDao.class.getSimpleName();
	public static final long ARRADY_EXISTS_THIS_FILED = -2;
	public static final long INSERT_ERROR = -1;

	public long insertPreUploadObject(PreUploadObject preuploadObj) {
		long row = INSERT_ERROR;
		try {
			PreUploadObject localPre = getPreUploadObject(preuploadObj.getOwnerId(), preuploadObj.getFolderId(), preuploadObj.getIdentity());
			
			if(null != localPre){
				LogUtil.e(TAG , "fileDao no need insertFile, id identical");
				return ARRADY_EXISTS_THIS_FILED;
			}
			row = this.getDb().insert(IPreUploadDao.TABLE_NAME, null, preuploadObj.toContentValues());
		} catch (Exception e) {
			LogUtil.e(TAG, "insert preupload record failure:" + e.getLocalizedMessage());
		}
		return row;
	}
	
	public PreUploadObject getPreUploadObject(String ownerId, String folderId, String identity) {
		
		PreUploadObject result = null;
		
		if(!StringUtil.isBlank(ownerId) 
				&& !StringUtil.isBlank(folderId) 
				&& !StringUtil.isBlank(identity)) {
			StringBuilder sb = new StringBuilder("select * from ");
			sb.append(IPreUploadDao.TABLE_NAME);
			sb.append("  where ");
			sb.append(IPreUploadDao.OWNER_ID).append("=?").append(" and ");
			sb.append(IPreUploadDao.FOLDER_ID).append("=?").append(" and ");
			sb.append(IPreUploadDao.FILE_IDENTITY).append("=?");
			
			Cursor cursor = this.getDb().rawQuery(sb.toString(), new String[] { ownerId, folderId, identity});
			
			if(cursor != null) {
				if(cursor.getCount() > 0 && cursor.moveToFirst()) {
					result = new PreUploadObject();
					result.fromCursor(cursor);
				}
				cursor.close();
			}
		}
		
		return result;
	}
	
	public int updataPreUploadObject(PreUploadObject preUploadObj) {
		int res = -1;
		if(preUploadObj != null) {
			String where = IPreUploadDao.OWNER_ID + "=? and "
							+IPreUploadDao.FOLDER_ID +"=? and "
							+IPreUploadDao.FILE_IDENTITY+"=?";
			String[] whereValue = { preUploadObj.getOwnerId(),preUploadObj.getFolderId(), preUploadObj.getIdentity()};
			
			res = this.getDb().update(IPreUploadDao.TABLE_NAME,preUploadObj.toContentValues(), where, whereValue);
		}
		return res;
	}
	
	@Override
	public long getLastUpdateTime(String objectId) {
		return 0;
	}
	
	@Override
	public void updateLastUpdateTime(String objectId) {
	}

}